﻿using NAnt.Core;
using NAnt.Core.Attributes;

namespace Sentient.Nant.Tasks
{
    [TaskName("db.create")]
    public class CreateDatabaseTask : NHibernateTask
    {
        private string _database;

        [TaskAttribute("database", Required = true)]
        public string Database
        {
            get { return _database; }
            set { _database = value;}
        }

        protected override void ExecuteTask()
        {
            try
            {
                CreateDatabaseIfNotExists(_database);
            }
            catch
            {
                Log(Level.Error, "Error creating database: {0}\n{1}", _database, ConnectionString);
                throw;
            }
        }

        protected void CreateDatabaseIfNotExists(string databaseName)
        {
            Catalog = "master";
            Log(Level.Info, "Creating database ({0})", databaseName);
            RunSqlCommand(
                string.Format("IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'{0}') CREATE DATABASE {0}",
                              databaseName));
        }

    }
}
